package com.xiaobai.service.oss;

import com.alibaba.fastjson.JSON;
import com.qiniu.cdn.CdnManager;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @author: 小白白
 * @create: 2021-11-26
 **/

@Service
@Slf4j
@Order(1)
public class QiNiuService implements IOSSService, ApplicationRunner {

    // 七牛云URL格式
    private static final String oosBaseUrl = "http://image.xiaobaibai.work/";
    private static final String fileNamePre = "freeClassroom/%s";

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    private Auth auth;
    private Configuration cfg;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        this.auth = Auth.create(accessKey, secretKey);
        this.cfg = new Configuration(Region.region2());
    }

    @Override
    public String uploadContent(byte[] bytes, String fileName) {
        fileName = String.format(fileNamePre, fileName);
        UploadManager uploadManager = new UploadManager(cfg);
        String upToken = auth.uploadToken(bucket, fileName); // 后跟fileName代表覆盖上传
        try {
            uploadManager.put(bytes, fileName, upToken);
            log.info("文件上传成功:{}", fileName);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return oosBaseUrl + fileName;
    }

    @Override
    public void refreshByUriCDN(String[] preUrls) {
        CdnManager cdnManager = new CdnManager(auth);
        try {
            cdnManager.refreshDirs(preUrls);
            log.info("CDN刷新成功:{}", JSON.toJSONString(preUrls));
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void refreshByFileCDN(String... fileUrl) {
        CdnManager cdnManager = new CdnManager(auth);
        try {
            cdnManager.refreshUrls(fileUrl);
            log.info("CDN刷新成功:{}", JSON.toJSONString(fileUrl));
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteFile(String fileName) {
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, fileName);
            log.info("文件删除成功:{}", fileName);
        } catch (QiniuException e) {
            // 目标文件不存在,则忽略
        }
    }
}
